package com.platform.api.bzproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.api.bzproject.model.BzTalent;
import com.platform.api.bzproject.model.User;
import com.platform.api.bzproject.service.IBzTalentService;
import com.platform.api.bzproject.service.UserService;
import com.platform.api.bzproject.vo.OnlineUserVo;
import com.platform.common.core.Result;
import com.platform.security.constants.SecurityConstants;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author guoyunfei on 2022/3/9 23:57
 * @className OnlineUserController
 * @description TODO 获取在线用户信息
 * @Version 1.0
 */

@RestController
@RequestMapping("/online")
public class OnlineUserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private  ConsumerTokenServices consumerTokenServices;
    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private IBzTalentService iBzTalentService;

    @GetMapping("/getOnlineUser")
    public Result getOnlineUser() {
        List<OnlineUserVo> onlineUserList = getOnlineUserList(null);
        return Result.success(onlineUserList);
    }

    /**
     * 根据用户ID删除redis缓存
     * @param u
     * @return
     */
    @GetMapping("/clearUser/{u}")
    public boolean clearUser(@PathVariable("u") String u) {

        List<OnlineUserVo> onlineUserList = getOnlineUserList(u);

        List<OnlineUserVo> list = onlineUserList.stream().filter(item -> item.getUserId().equals(u)).collect(Collectors.toList());

        if(list.size() > 0){
            return consumerTokenServices.revokeToken(list.get(0).getToken());
        }
        return false;
    }


    public List<OnlineUserVo> getOnlineUserList(String disUserId) {
        List<OnlineUserVo> list = new ArrayList<>();
        //oauth存放的所有keys
        Set<String> keys = redisTemplate.keys(SecurityConstants.PLATFORM_OAUTH_PREFIX + "auth:" + "*");
        for (String key : keys) {
            //keys = "auth:" + token
            //根据token获取OAuth2AccessToken
            String token = key.substring(key.indexOf(":") + 1);
            //根据token值获取OAuth2AccessToken对象
            //575384e3-4be7-4e80-b4e0-d8dbc0105286
            token = token.split(":")[1];
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);

            //获取用户id，本项目用户id存放在OAuth2AccessToken对象中的additionalInformation属性里。
            //根据实际情况修改
            Map<String, Object> map = oAuth2AccessToken.getAdditionalInformation();
            if (map != null) {
                //获取用户id
                String userId = (String) map.get("userId");
                if(null != disUserId){
                    if(!disUserId.equals(userId)){
                        //获取单个用户
                        continue;
                    }
                }

                if (userId != null) {
                    //获取用户信息
                    List<BzTalent> talents = iBzTalentService.list(new QueryWrapper<BzTalent>().eq("userid", userId));
                    if(talents.size() > 0){
                        OnlineUserVo onlineUserVo = new OnlineUserVo();
                        onlineUserVo.setToken(token);
                        onlineUserVo.setUserId(userId);
                        onlineUserVo.setName(talents.get(0).getNickname());
                        onlineUserVo.setExpiration( oAuth2AccessToken.getExpiration());
                        onlineUserVo.setExpiresIn(oAuth2AccessToken.getExpiresIn());
                        list.add(onlineUserVo);
                    }

                }
            }
        }
        return list;
    }

}
